package com.hzhh123.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;
/**
 * 
 * @author hzhh123
 * @Date 2019年2月27日 下午1:36:00
 * 五、分散(Scatter)与聚集(Gather)
 * 分散读取（Scattering Reads）：将通道中的数据分散到多个缓冲区中
 * 聚集写入（Gathering Writes）：将多个缓冲区中的数据聚集到通道中
 * 
 * 六、字符集：Charset
 * 编码：字符串 -> 字节数组
 * 解码：字节数组  -> 字符串
 */
public class TestChannel {

	/**
	 * 分散(Scatter)与聚集(Gather)
	 * @throws Exception 
	 */
	@Test
	public void test4() throws Exception {
		RandomAccessFile rf1=new RandomAccessFile("1.txt", "rw");
		//获取通道
		FileChannel channel=rf1.getChannel();
		//分配缓冲区
		ByteBuffer buf1=ByteBuffer.allocate(10);
		ByteBuffer buf2=ByteBuffer.allocate(1024);
		ByteBuffer[] buf=new ByteBuffer[] {buf1,buf2};
		//分散读取
		channel.read(buf);
		for(ByteBuffer b:buf) {
			b.flip();//切换读写模式
		}
		System.out.println(new String(buf[0].array(),0,buf[0].limit()));
		System.out.println("-----------------");
		System.out.println(new String(buf[1].array(),0,buf[1].limit()));
		
		//聚集写入
		RandomAccessFile rf2=new RandomAccessFile("2.txt", "rw");
		FileChannel channel2=rf2.getChannel();
		channel2.write(buf);
	}
	
	/**
	 * 查出系统所有编码
	 */
	@Test
	public void test5() {
		Map<String,Charset>sc=Charset.availableCharsets();
		Set<Entry<String,Charset>>set=sc.entrySet();
		for(Entry<String,Charset>en:set) {
			System.out.println(en.getKey()+"----"+en.getValue());
		}
	}
	
	/**
	 * 字符集
	 * @throws IOException
	 */
	@Test
	public void test6() throws IOException {
		Charset c1=Charset.forName("GBK");
		//获取编码器
		CharsetEncoder 	cen1=c1.newEncoder();
		//获取解码器
		CharsetDecoder cd1=c1.newDecoder();
		
		CharBuffer charBuffer=CharBuffer.allocate(1024);
		charBuffer.put("测试");
		charBuffer.flip();
		
		//编码
		ByteBuffer buf=cen1.encode(charBuffer);
		for(int i=0;i<4;i++) {
			System.out.println(buf.get());
		}
		
		//解码
		buf.flip();
		CharBuffer cb2=cd1.decode(buf);
		System.out.println(cb2.toString());
		System.out.println("------------------------------------------------------");
		
		Charset cs2 = Charset.forName("GBK");
		buf.flip();
		CharBuffer cBuf3 = cs2.decode(buf);
		System.out.println(cBuf3.toString());
	}
}
